package com.github.doobo.handler;

import com.alibaba.fastjson.JSON;
import com.github.doobo.bo.IpfsNodeInfo;
import com.github.doobo.bo.PubMessageBO;
import com.github.doobo.bo.PubMsgEncodeBO;
import com.github.doobo.utils.IpAddressUtils;
import com.github.doobo.vbo.Builder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Objects;

/**
 * 节点信息通知
 *
 * @Description: ipfs-cloud
 * @User: diding
 * @Time: 2022-12-19 17:53
 */
@Slf4j
@Component
public class PlatformCidNotifyHandler extends AbstractPlatformMsgHandler {

	public boolean isMatchBody(PubMessageBO body){
		if(Objects.isNull(body)){
			return false;
		}
		IpfsNodeInfo info = AbstractPlatformInitHandler.RESPONSE.getInfo();
		if(Objects.isNull(info)){
			return false;
		}
		return "ipfs/addBootstrap/notify".equals(body.getUri())
			&& !Objects.equals(info.getCid(), body.getFrom());
	}

	@Override
	public void handler(PubMessageBO body, PubMsgEncodeBO msg) {
		if(!isMatchBody(body)){
			return;
		}
		IpfsNodeInfo info = AbstractPlatformInitHandler.RESPONSE.getInfo();
		IpfsNodeInfo tmp = Builder.of(IpfsNodeInfo::new)
			.with(IpfsNodeInfo::setCid, info.getCid())
			.with(IpfsNodeInfo::setIp, info.getIp())
			.with(IpfsNodeInfo::setPort, info.getPort())
			.with(IpfsNodeInfo::setPublicKey, info.getPublicKey())
			.with(IpfsNodeInfo::setAgentVersion, info.getAgentVersion())
			.with(IpfsNodeInfo::setProtocolVersion, info.getProtocolVersion())
			.build();
		if(Objects.isNull(tmp.getIp()) || tmp.getIp().contains("localhost")
			|| tmp.getIp().contains("127.0")){
			tmp.setIp(IpAddressUtils.getLocalAddress());
		}
		PubMessageBO bo = Builder.of(PubMessageBO::new)
			.with(PubMessageBO::setType, "single")
			.with(PubMessageBO::setMethod, "POST")
			.with(PubMessageBO::setTarget, body.getFrom())
			.with(PubMessageBO::setUri, "ipfs/addBootstrap/callback")
			.with(PubMessageBO::setBody, JSON.toJSONString(Collections.singletonList(tmp)))
			.build();
		AbstractPlatformInitHandler.pubMessage(bo);
	}
}
